<template>
  <list-layout
    channel="tools">
    <div class="" style="padding-bottom: 30px;">
      <div class="config-wrapper no-select"
        :class="{
          'width-bottom-border': !data.presetVms?.length,
        }">
        <div
          v-for="(cat, idx) in categories" :key="idx" class="config-item row no-wrap items-center">
          <div class="config-item-title">{{ cat.title }}</div>
          <div class="config-item-line"></div>
          <div class="config-item-options row col">
            <div
              :class="{
                active: selected[cat.value] === opt.value,
                disable: opt.disable ||
                  (optionFilter[cat.value] && optionFilter[cat.value][opt.value] === false),
              }"
              class="config-item-options-item"
              square
              v-for="(opt, oidx) in cat.options" :key="oidx"
              @click="select(cat, opt)">{{ opt.label }}</div>
          </div>
        </div>
      </div>

      <div class="ula q-mt-md">
        <div class="ula-item warning" v-show="!hasVMs">
          <span class="warning-sign">⚠️</span>没有可用的云资源，请稍后再试！
        </div>
        <div class="ula-item warning" v-show="data.using">
          <span class="warning-sign">⚠️</span>
          您正在占用云资源，请继续使用，或释放！
          <span class="release-span">
            <q-btn icon="delete" flat dense size="sm" @click="releaseVM"></q-btn>
          </span>
        </div>
        <div class="ula-item" v-show="hasVMs">
          <q-checkbox v-model="aggreement">勾选本项代表您已仔细阅读并同意《<a href="">用户协议</a>》。</q-checkbox>
        </div>
      </div>
      <div class="row full-width justify-end no-wrap q-pl-md" style="margin-top: -48px">
        <q-btn @click="startVm" flat
          :disable="!aggreement || ((!hasVMs || !selectedAll) && !data.using)"
          class="start-btn bg-primary text-white" style="min-width: 100px">启动</q-btn>
      </div>
      <q-separator class="q-mt-lg" v-if="data.presetVms?.length"/>
      <div class="pre-set-vms full-width row q-gutter-md q-mt-xs">
        <q-btn
          flat
          no-caps
          class="vm-short-cut q-px-md q-py-xs q-mr-lg"
          color="#00000099"
          style="border-radius: 10px;border: 1px solid rgba(0, 0, 0, 0.2);font-family: Roboto;"
          v-for="(vm, idx) in data.presetVms || []" :key="idx"
          :label="vm.label"
          @click="openPresetVM(vm)">
          <q-tooltip v-if="vm.description">{{ vm.description }}</q-tooltip>
        </q-btn>
      </div>
    </div>
  </list-layout>
</template>

<script>
import mixins from 'eis-admin-mixins';
import { GoHomeOnLocaleChange } from '../../components/mixins/locale';
import listLayout from '../../components/listLayout.vue';

export default {
  name: 'OnlineTestPortal',
  mixins: [mixins.ObjectDataMixin, GoHomeOnLocaleChange],
  components: {
    listLayout,
  },
  data() {
    return {
      categories: [
        {
          title: '计算配置',
          value: 'base',
          options: [
            {
              label: '4c8g',
              value: '4c8g',
            },
          ],
        },
        {
          title: 'GPU',
          value: 'gpu',
          options: [
            {
              label: '英伟达',
              value: 'nvidia',
            },
            {
              label: '天数',
              value: '天数',
            },
            {
              label: '华为(arm)',
              value: '华为',
            },
            {
              label: '百度',
              value: '百度',
            },
            {
              label: '寒武纪',
              value: '寒武纪',
            },
            {
              label: '燧原',
              value: '燧原',
            },
          ],
        },
        {
          title: '操作系统',
          value: 'os',
          options: [
            {
              label: 'Ubuntu',
              value: 'ubuntu',
            },
            {
              label: 'CentOS',
              value: 'centos',
            },
            {
              label: '银河麒麟',
              value: '银河麒麟',
            },
          ],
        },
        {
          title: 'AI框架',
          value: 'framework',
          options: [
            {
              label: 'PyTorch',
              value: 'pytorch',
            },
            {
              label: 'MindSpore',
              value: 'mindspore',
            },
            {
              label: 'PaddlePaddle',
              value: 'paddlepaddle',
            },
          ],
        },
      ],
      optionFilter: {},
      selected: {},
      aggreement: false,
    };
  },
  computed: {
    hasVMs() {
      if (!this.data) {
        return true;
      }

      if (typeof this.data?.valid !== 'boolean') {
        return true;
      }

      return this.data?.valid === true;
    },
    selectedAll() {
      return Object.keys(this.selected).length === this.categories?.length;
    },
  },
  methods: {
    afterRefresh() {
      if (!this.data || !this.data.opts) return;

      this.categories.forEach((cat) => {
        cat.options.forEach((opt) => {
          if ((this.data.opts[cat.value] || []).indexOf(opt.value) === -1) {
            opt.disable = true;
          }
        });
      });

      if (this.data.selected) {
        this.selected = this.data.selected;
      }

      this.data.vms = this.data.vms.map((vm) => {
        const [base, gpu, os, framework] = vm.label.split('-');

        return {
          ...vm,
          base,
          gpu,
          os,
          framework,
        };
      });
    },
    select(cat, opt) {
      if (!this.hasVMs || this.data.using || opt.disable
        || (this.optionFilter[cat.value] && this.optionFilter[cat.value][opt.value] === false)) {
        return;
      }

      if (this.selected[cat.value] === opt.value) {
        this.$set(this.selected, cat.value, undefined);
        delete this.selected[cat.value];
      } else {
        this.$set(this.selected, cat.value, opt.value);
      }

      // 根据已经选择的配置，设定其他选项是否可选
      const filter = {};

      Object.keys(this.data.opts).forEach((key) => {
        filter[key] = {};
        this.data.opts[key].forEach((value) => {
          filter[key][value] = false;
        });
      });

      const leftVms = this.data.vms.filter(
        (vm) => Object.keys(this.selected).every((key) => vm[key] === this.selected[key]),
      );

      for (let i = 0; i < leftVms.length; i += 1) {
        const vm = leftVms[i];
        delete filter.base[vm.base];
        delete filter.gpu[vm.gpu];
        delete filter.os[vm.os];
        delete filter.framework[vm.framework];
      }

      this.optionFilter = filter;
    },
    startVm() {
      const theVM = this.data.using ? {
        id: this.data.using,
      } : this.data.vms.find((vm) => vm.label === `${this.selected.base}-${this.selected.gpu}-${this.selected.os}-${this.selected.framework}`);

      if (!theVM) {
        this.$q.notify('没有可用的云资源');
        return;
      }

      // 设置一个localStorage，用于判断服务器连接页面是否是从此页面打开的
      localStorage.setItem('fromOnlineTest', Date.now());

      window.open(`/test/vm/${theVM.id}`, '_blank');
    },
    releaseVM() {
      if (!this.data.using) {
        return;
      }

      this.$q.dialog({
        title: '释放云资源',
        message: '确定要释放云资源吗？释放后将无法恢复。',
        cancel: '取消',
        ok: '确定',
        persistent: true,
      }).onOk(() => {
        this.postRequest('/cloud/vm/release', {
          vm: this.data.using,
        }).then(() => {
          this.$q.notify('云资源已释放');
          this.refreshData();

          this.selected = {};
        });
      });
    },

    openPresetVM(vm) {
      if (!vm?.id) return;

      // 设置一个localStorage，用于判断服务器连接页面是否是从此页面打开的
      localStorage.setItem('fromOnlineTest', Date.now());
      window.open(`/test/vm/${vm.id}`, '_blank');
    },
  },
};
</script>

<style lang="scss" scoped>
.config-wrapper {
  &.width-bottom-border {
    border-bottom: 1px solid rgba(0, 0, 0, 0.1);
    padding-bottom: 40px;
  }

  .config-item {
    padding: 24px 16px;
    position: relative;

    &-title {
      font-size: 16px;
      width: 120px;
      text-align: center;
      color: #555;
      position: relative;
    }

    &-options {
      padding-left: 32px;
      border-left: 1px solid rgba(0, 0, 0, 0.1);

      .config-item-options-item {
        width: 120px;
        height: 50px;
        line-height: 50px;
        border-radius: 10px;
        font-size: 14px;
        text-align: center;
        font-family: Roboto;

        color: rgba(0, 0, 0, 0.8);
        border: 1px solid rgba(0, 0, 0, 0.2);
        cursor: pointer;

        margin-bottom: 8px;
        margin-top: 8px;

        &:not(:nth-child(5n)) {
          margin-right: 60px;
        }

        &.active {
          border: 1px solid rgba(78, 134, 230, 1);
          background-color: rgba(255, 255, 255, 1);
          color: rgba(78, 134, 230, 1);
        }

        &.disable {
          color: rgba(204, 204, 204, 1);
          cursor: not-allowed;
        }
      }
    }
  }
}

.start-btn {
  // margin-top: 16px;
  // margin-right: 32px;
  border-radius: 10px;

  width: 120px;
  height: 50px;
  line-height: 23px;
  border-radius: 10px;
  background-color: rgba(78, 134, 230, 1);
  color: rgba(204, 204, 204, 1);
  font-size: 16px;
  text-align: center;
  font-family: Roboto;
}

.ula {
  &-item {
    font-size: 14px;
    color: rgba(0, 0, 0, 0.6);
    margin-right: 16px;

    &.warning {
      color: rgba(255, 0, 0, 1);

      .warning-sign {
        font-family: system-ui;
        font-size: 16px;
        margin-right: 8px;
        margin-left: 12px;
      }
    }
  }
}
</style>
